import json
import pandas as pd
import os
from bs4 import BeautifulSoup
from typing import List, Dict, Any
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter


def extract_pdf_content_from_json(json_file_path: str) -> List[List[str]]:
    """
    从JSON文件中提取PDF的实际内容

    Args:
        json_file_path: JSON文件路径

    Returns:
        包含PDF内容的二维列表
    """
    try:
        with open(json_file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        content_rows = []

        # 添加文件标识
        content_rows.append([f"=== 文件: {os.path.basename(json_file_path)} ==="])
        content_rows.append([])  # 空行

        # 处理解析结果列表中的内容块
        parsing_res_list = data.get('parsing_res_list', [])

        for block in parsing_res_list:
            block_label = block.get('block_label', '')
            block_content = block.get('block_content', '').strip()

            # 跳过空内容
            if not block_content:
                continue

            # 处理不同类型的块
            if block_label == 'table':
                # 表格内容 - 解析HTML表格
                try:
                    soup = BeautifulSoup(block_content, 'html.parser')
                    table = soup.find('table')
                    if table:
                        # 提取所有行
                        rows = table.find_all('tr')
                        for row in rows:
                            # 提取单元格文本
                            cells = [td.get_text(strip=True) for td in row.find_all(['td', 'th'])]
                            if cells:  # 只添加非空行
                                content_rows.append(cells)
                        content_rows.append([])  # 表格后添加空行
                except Exception as e:
                    print(f"表格解析错误: {str(e)}")
                    # 如果解析失败，添加原始内容
                    content_rows.append(["表格内容:"])
                    content_rows.append([block_content])
                    content_rows.append([])

            elif block_label in ['text', 'header', 'paragraph_title', 'footer']:
                # 文本内容（包括页脚）- 按行分割
                lines = block_content.split('\n')
                for line in lines:
                    line = line.strip()
                    if line:  # 只添加非空行
                        content_rows.append([line])
                content_rows.append([])  # 文本块后添加空行

            # 忽略其他类型的块（如seal等）

        return content_rows

    except Exception as e:
        print(f"提取文件 {json_file_path} 内容时出错: {str(e)}")
        return [[f"错误: 无法提取 {json_file_path} 的内容"]]


def auto_adjust_column_width(worksheet):
    """
    自动调整Excel列宽以适应内容

    Args:
        worksheet: Excel工作表对象
    """
    for column_cells in worksheet.columns:
        # 获取列字母
        column_letter = get_column_letter(column_cells[0].column)

        # 计算该列中最长内容的长度
        max_length = 0
        for cell in column_cells:
            try:
                if cell.value:
                    # 计算单元格内容的长度（考虑换行符）
                    cell_lines = str(cell.value).split('\n')
                    max_line_length = max(len(line) for line in cell_lines)
                    max_length = max(max_length, max_line_length)
            except:
                pass

        # 设置列宽，添加一些额外空间
        adjusted_width = min(max_length + 2, 50)  # 限制最大宽度为50
        worksheet.column_dimensions[column_letter].width = adjusted_width


def auto_adjust_row_height(worksheet):
    """
    自动调整Excel行高以适应内容

    Args:
        worksheet: Excel工作表对象
    """
    for row in worksheet.iter_rows():
        for cell in row:
            if cell.value:
                # 计算单元格中的行数
                line_count = len(str(cell.value).split('\n'))
                if line_count > 1:
                    # 设置行高，每行大约15点
                    worksheet.row_dimensions[cell.row].height = line_count * 15

                # 设置文本自动换行
                cell.alignment = Alignment(wrap_text=True)


def export_pdf_content_to_excel(json_file_paths: List[str], output_excel_path: str):
    """
    将多个JSON文件中的PDF内容转换为Excel

    Args:
        json_file_paths: JSON文件路径列表
        output_excel_path: 输出的Excel文件路径
    """

    # 收集所有内容
    all_content = []

    for json_file_path in json_file_paths:
        file_content = extract_pdf_content_from_json(json_file_path)
        all_content.extend(file_content)

        # 文件之间添加分隔行
        all_content.append(["=" * 50])
        all_content.append([])

    if not all_content:
        return

    # 创建Excel文件
    try:
        # 找到最大列数
        max_cols = max(len(row) for row in all_content)

        # 确保所有行都有相同的列数
        padded_data = [row + [''] * (max_cols - len(row)) for row in all_content]

        # 创建DataFrame
        df = pd.DataFrame(padded_data)

        # 确保输出目录存在
        os.makedirs(os.path.dirname(output_excel_path), exist_ok=True)

        # 写入Excel
        df.to_excel(output_excel_path, index=False, header=False, engine='openpyxl')

        # 加载工作簿以调整列宽和行高
        workbook = load_workbook(output_excel_path)
        worksheet = workbook.active

        # 自动调整列宽和行高
        auto_adjust_column_width(worksheet)
        auto_adjust_row_height(worksheet)

        # 保存调整后的工作簿
        workbook.save(output_excel_path)

    except Exception as e:
        print(f"生成Excel文件时出错: {str(e)}")


def export_pdf_folder_to_excel(folder_path: str, output_excel_path: str):
    """
    将文件夹中所有JSON文件中的PDF内容转换为Excel

    Args:
        folder_path: 包含JSON文件的文件夹路径
        output_excel_path: 输出的Excel文件路径
    """
    json_files = []

    # 查找所有JSON文件
    for file in os.listdir(folder_path):
        if file.endswith('.json'):
            json_files.append(os.path.join(folder_path, file))

    # 按文件名排序（确保page1在前，page2在后）
    json_files.sort()

    if not json_files:
        print(f"在文件夹 {folder_path} 中没有找到JSON文件")
        return

    # print(f"找到 {len(json_files)} 个JSON文件")
    export_pdf_content_to_excel(json_files, output_excel_path)


if __name__ == "__main__":
    json_files = [
        "output_structure/2f9f3436-91cd-466c-859a-40e08b7c77d9/page1.json",
        "output_structure/2f9f3436-91cd-466c-859a-40e08b7c77d9/page2.json",
        "output_structure/2f9f3436-91cd-466c-859a-40e08b7c77d9/page3.json",
        "output_structure/2f9f3436-91cd-466c-859a-40e08b7c77d9/page4.json"
    ]

    output_file = "output_structure/result.xlsx"

    export_pdf_content_to_excel(json_files, output_file)